import { defineStore } from 'pinia'

import { loginApi, logoutApi } from '@/api/auth'
import { getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { store } from '@/store'

import { LoginData } from '@/api/auth/types'
import { UserInfo } from '@/api/user/types'

import { useStorage } from '@vueuse/core'

export const useUserStore = defineStore('user', () => {
  // state
  const token = useStorage('accessToken', '')
  const nickname = ref('')
  const avatar = ref('')
  const roles = ref<Array<string>>([]) // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]) // 用户权限编码集合 → 判断按钮权限

  /**
   * 登录调用
   *
   * @param {LoginData}
   * @returns
   */
  async function login(loginData: LoginData) {
    const response = await loginApi(loginData)
    token.value = response.data.token // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(({ data }) => {
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const { menus, points } = data.roles
          if (!menus || menus.length <= 0) {
            reject('getUserInfo: roles must be a non-null array!')
          }
          nickname.value = data.name
          avatar.value = data.avatar
          roles.value = menus
          perms.value = points
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetRouter()
          resetToken()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  }

  // 重置
  function resetToken() {
    token.value = ''
    nickname.value = ''
    avatar.value = ''
    roles.value = []
    perms.value = []
  }

  return {
    token,
    nickname,
    avatar,
    roles,
    perms,
    login,
    getInfo,
    logout,
    resetToken
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
